import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { conditionLikeUtils } from '../../utils/db.helper';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { getBookDto } from './dto/get-book.dto';
import { Book } from './book.entity';
import * as fs from 'fs';
import * as path from 'path';
import BookEpubParse from './book-epub-parse';
import { Category } from './category.entity';
import { BOOK_PATH } from '../../utils/const'

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book)
    private readonly bookRepository: Repository<Book>,

    @InjectRepository(Category)
    private readonly categoryRepository: Repository<Category>,
  ) {}

  addBook(createBookDto: CreateBookDto, username: string) {
    let now = new Date();
    let month: string = now.getMonth() + 1 + '';
    if (parseInt(month) < 10) month = '0' + month;
    let day: string = now.getDate() + '';
    if (parseInt(day) < 10) day = '0' + day;
    let date = now.getFullYear() + month + day;
    // console.log("🚀 ~ BookService ~ addBook ~ date:", date)
    createBookDto.createUser = username;
    createBookDto.createDt = parseInt(date);
    // console.log("🚀 ~ BookService ~ create ~ createBookDto:", createBookDto)

    const book = this.bookRepository.create(createBookDto);
    return this.bookRepository.save(book);
  }

  findAll() {
    return this.bookRepository.find();
  }

  findCategoryAll() {
    return this.categoryRepository.find();
  }

  getBook(id: number) {
    return this.bookRepository.findOne({where: {id}});
  }

  getBookList(query: getBookDto) {
    const { limit, page, title, author } = query;
    const take = limit || 10;
    const skip = ((page || 1) - 1) * take;

    const queryBuilder = this.bookRepository
      .createQueryBuilder('book')
      // .select(COVER_PATH_PREFIX + 'book.cover', 'cover')
      .leftJoinAndSelect('book.category', 'category')
    const obj = {
      'title': title,
      'author': author
    }
    // console.log("🚀 ~ BookService ~ getBookList ~ obj:", obj)
    const newQuery = conditionLikeUtils<Book>(queryBuilder, obj)
    return newQuery
     .take(take)
     .skip(skip)
     .getMany();
  }

  getBookCount(query: getBookDto) {
    const { title, author } = query;

    const queryBuilder = this.bookRepository.createQueryBuilder('book').select('COUNT(1) as count')
    const obj = {
      'title': title,
      'author': author
    }
    const newQuery = conditionLikeUtils<Book>(queryBuilder, obj)
    return newQuery.getRawMany();
  }

  uploadFile(file: Express.Multer.File){
    // const destDir = 'F:/nginx-1.24.0/upload'
    const fileName = decodeURIComponent(file.originalname)
    const destPath = path.resolve(BOOK_PATH, fileName).replace(/\\/g, '/')
    console.log("🚀 ~ BookService ~ uploadFile ~ destPath:", destPath)
    fs.writeFileSync(destPath, file.buffer)
    // 电子书解析
    return this.parseBook(destPath, file).then((data) => {
      return {
        originalname: fileName,
        mimetype: file.mimetype,
        size: file.size,
        path: destPath,
        dir: BOOK_PATH,
        data
      }
    })
  }

  parseBook(filePath: string, file: Express.Multer.File) {
    const epub = new BookEpubParse(filePath, file);
    return epub.parse();
  }

  async remove(id: number): Promise<Book> {
    const book = await this.bookRepository.findOne({where: {id}})
    return this.bookRepository.remove(book)
  }

  findOne(id: number) {
    return `This action returns a #${id} book`;
  }

  update(id: number, updateBookDto: UpdateBookDto) {
    return `This action updates a #${id} book`;
  }

}
